<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row :gutter="48">
          <a-col :span="12">
            <a-form-model-item label="业务分类编码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="categoryCode">
              <!--              <a-input :disabled=formDisabled v-model="model.categoryCode" placeholder="请输入业务分类编码"  ></a-input>-->
              <business-category-select
                  :disabled="disableOld"
                  v-model="model.categoryCode" @back="businessCategoryHandle"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="业务分类名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="categoryName">
              <a-input  :disabled="formDisabled || disableOld" v-model="model.categoryName" placeholder="请输入业务分类名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="合同占比（%）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractRate">
              <a-input-number :disabled='formDisabled || distributionMethod=="2"' :max="99999999" :min="0" v-model="model.contractRate" @change="handleRateChange"
                              placeholder="请输入合同占比" style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="分配合同额（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractAmount">
              <a-input-number :disabled='formDisabled || distributionMethod=="1"' :max="99999999" :min="0" v-model="model.contractAmount" @change="handleAmountChange"
                              placeholder="请输入分配合同额" style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="生产团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="productTeam">
              <!--<a-input :disabled=formDisabled v-model="model.sctd" placeholder="请输入生产团队"  ></a-input>-->
              <select-team-input
                  v-model="model.productTeam"
                  :tdlx="2"
                  @change="productTeamChange"
                  :triggerChange="true"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="团队负责人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamLeader">
              <!--<a-input :disabled=formDisabled v-model="model.tdfzr" placeholder="请输入团队负责人"  ></a-input>-->
              <select-user-by-dep v-model="model.teamLeader"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="任务说明" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="taskDescription">
              <a-textarea  :disabled="disableOld" :max-length="500" v-model="model.taskDescription" rows="4" placeholder="请输入任务说明"/>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

import { getAction } from '@/api/manage'
import BusinessCategorySelect from '@views/erp/components/BusinessCategorySelect';
import SelectTeamInput from '@views/scy/components/SelectTeamInput';
import SelectUserByDep from '@/views/scy/components/SelectUserByDep';

export default {
  name: 'ErpMyOmcProjectTaskForm',
  components: {
    BusinessCategorySelect, SelectTeamInput, SelectUserByDep
  },
  props: {
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    assignedAmount: {
      type: [Number, String],
      default: ''
    },
    // 1:按比例，2：按金额
    distributionMethod: {
      type: [Number, String],
      default: ''
    },
  },
  data() {
    return {
      model: {},
      labelCol: {},
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 },
      },
      confirmLoading: false,
      validatorRules: {
        categoryCode: [
          { required: true, message: '请输入业务分类编码' }
        ],
        categoryName: [
          { required: true, message: '请输入业务分类名称' }
        ],
        contractRate: [
          { required: true, message: '请输入合同占比' },
          // { pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }
          { pattern: /^-?(([0-9]*(\.[0-9]{1,3})$)|([0-9]+$))/, message: '请输入正确的比例!' }
        ],
        contractAmount: [
          { required: true, message: '请输入分配合同额' },
          // { pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }
          { pattern: /^-?(([0-9]*(\.[0-9]{1,3})$)|([0-9]+$))/, message: '请输入正确的金额!' }
        ],
        productTeam: [
          { required: true, message: '请输入生产团队' }
        ],
        teamLeader: [
          { required: true, message: '请输入团队负责人' }
        ]
      },
      url: {
        add: '/api/erp/omc/project/erpOmcProjectTask/add',
        edit: '/api/erp/omc/project/erpOmcProjectTask/edit',
        queryById: '/api/erp/omc/project/erpOmcProjectTask/queryById'
      },
      disabledOnly: false,
      disableOld: false,
      disableNew: false
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  watch: {
    assignedAmount: {
      handler: function(val){
        if (val) {
          let rate = this.model.contractAmount / val * 100
          this.model.contractRate = Math.round((rate + Number.EPSILON) * 100) / 100;
        } else {
          this.model.contractRate = '';
          this.model.contractAmount = '';
        }
      },
      immediate: true
    }
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
  },
  methods: {
    productTeamChange(val) {
      //debugger;
      getAction('/api/erp/omc/teammanager/erpOmcTeamManager/queryById', { id: val }).then((res) => {
        if (res.success) {
          // debugger;
          let data = res.result.records || res.result
          this.$set(this.model, 'productTeam', val)
          this.$set(this.model, 'teamLeader', data.tdfzr)
        }
      })
    },
    handleRateChange(e){
      if(this.assignedAmount !== 0){
        let amount = this.assignedAmount * e / 100
        this.model.contractAmount = Math.round((amount + Number.EPSILON) * 100) / 100;
      }else{
        this.model.contractAmount = 0
      }
    },
    handleAmountChange(e){
      if(this.assignedAmount !== 0){
        let rate = e / this.assignedAmount * 100
        this.model.contractRate = Math.round((rate + Number.EPSILON) * 100) / 100;
      }else{
        this.model.contractRate = 0
      }
    },
    businessCategoryHandle(obj) {
      if (obj) {
        this.model.categoryName = obj.categoryName
      }
    },
    add() {
      this.edit(this.modelDefault);
    },
    edit(record,flag) {
      this.$refs["form"].clearValidate();
      Object.assign(this.$data, this.$options.data())
      //this.$refs.form.resetFields();
      this.model = Object.assign({}, record);
      if(flag == '1'){
        this.disableNew = false
        this.disableOld = true
      }else{
        this.disableOld = false
        this.disableNew = false
      }
      this.visible = true;
    },
    submitForm() {
      const that = this;
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          //that.confirmLoading = true;
          getAction('/api/erp/omc/project/erpOmcProjectApply/valdateProductTeamLeader', { teamId: this.model.productTeam }).then((res) => {
            if (res.success) {
              if (!this.model.id) {
                this.model.id = parseInt(Math.random() * 1000000000000);
              }
              this.$emit('ok', this.model);
            } else {
              that.$message.warning(res.message);
            }
          })

          // let httpurl = '';
          // let method = '';
          // if (!this.model.id) {
          //   httpurl += this.url.add;
          //   method = 'post';
          // } else {
          //   httpurl += this.url.edit;
          //   method = 'put';
          // }
          // httpAction(httpurl, this.model, method).then((res) => {
          //   if (res.success) {
          //     that.$message.success(res.message);
          //     that.$emit('ok');
          //   } else {
          //     that.$message.warning(res.message);
          //   }
          // }).finally(() => {
          //   that.confirmLoading = false;
          // })
        }

      })
    },
  }
}
</script>
